import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_oa/beans/customer_bean.dart';
import 'package:flutter_oa/route/routes.dart';
import 'package:flutter_oa/utils/const.dart';
import 'package:flutter_oa/view/loading.dart';
import 'package:qrcode_reader/qrcode_reader.dart';

class Customer extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new ListState();
}

class ListState extends State<Customer> with AutomaticKeepAliveClientMixin {
  List<Map<String, dynamic>> maps = new List();
  List<DataListBean> dataList;
  var loadingDialog;
  Future<String> _barcodeString;

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  List<Widget> _doWidgets() {
    List<Widget> listTitles = new List();
    for (var i = 0; i < dataList.length; i++) {
      listTitles.add(buildListItem(context, dataList[i]));
    }
    return listTitles;
  }

  Widget buildListItem(BuildContext context, DataListBean bean) {
    return GestureDetector(
      onTap: () {
        String route = '${Routes.customerdetiail}';
        Routes.router.navigateTo(context, route,
            replace: false, transition: TransitionType.fadeIn);
      },
      child: Card(
        child: Padding(
          padding: const EdgeInsets.all(12.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        bean.name,
                        style: TextStyle(color: Colors.black, fontSize: 14),
                      ),
                      Container(
                          margin: EdgeInsets.fromLTRB(5, 0, 5, 0),
                          width: 1,
                          height: 14,
                          color: Colors.grey),
                      Text(
                        '',
                        style: TextStyle(color: Colors.grey, fontSize: 14),
                      ),
                    ],
                  ),
                  Text(
                    '',
                    style: TextStyle(color: Colors.green, fontSize: 16),
                  ),
                ],
              ),
              Container(
                margin: EdgeInsets.all(5),
                color: Colors.grey[200],
                height: 1,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Icon(
                    Icons.phone,
                    color: Colors.grey,
                    size: 14,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '客户电话:',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Column(
                    children: <Widget>[
                      SizedBox(
                        height: 2,
                      ),
                      Text(
                        bean.phone,
                        style: TextStyle(fontSize: 14, color: Colors.blue),
                      ),
                      SizedBox(
                        height: 5,
                      ),
                      Text(
                        bean.address,
                        style: TextStyle(fontSize: 14, color: Colors.blue),
                      ),
                    ],
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Icon(
                    Icons.home,
                    color: Colors.grey,
                    size: 14,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '施工小区:',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '施工小区:',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Icon(
                    Icons.location_on,
                    color: Colors.grey,
                    size: 14,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '详细地址:',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '施工小区:',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Icon(
                    Icons.person,
                    color: Colors.grey,
                    size: 14,
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '接待人员:',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  SizedBox(
                    width: 5,
                  ),
                  Text(
                    '白洁',
                    style: TextStyle(fontSize: 14, color: Colors.grey),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(3.0),
                    child: Icon(
                      Icons.phone,
                      color: Colors.blue,
                      size: 14,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _getHttp();
  }

  _showDialog(String text) {
    loadingDialog = LoadingDialog(
      text: text,
    );
    showDialog<Null>(
        context: context,
        barrierDismissible: false, //外部触摸
        builder: (BuildContext context) {
          return loadingDialog;
        });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(
          '客户',
          style: TextStyle(color: Colors.black),
        ),
        backgroundColor: Colors.grey[200],
        leading: IconButton(
            icon: Icon(
              Icons.scanner,
              color: Colors.black,
            ),
            onPressed: () {
              setState(() {
                _barcodeString = QRCodeReader()
                    .setAutoFocusIntervalInMs(200)
                    .setForceAutoFocus(true)
                    .setTorchEnabled(true)
                    .setHandlePermissions(true)
                    .setExecuteAfterPermissionGranted(true)
                    .setFrontCamera(false)
                    .scan();
              });
            }),
        actions: <Widget>[
          IconButton(
              icon: Icon(
                Icons.search,
                color: Colors.green,
              ),
              onPressed: () {
                _showDialog('正在获取详情...');
                _getHttp();
              }),
        ],
        elevation: 0.0,
      ),
      body: Container(
        color: Colors.grey[200],
        padding: EdgeInsets.fromLTRB(10, 0, 10, 10),
        child: Column(
          children: <Widget>[
            IconButton(
                icon: Icon(
                  Icons.add,
                  color: Colors.grey,
                ),
                onPressed: () {
//              Navigator.pop(context);
                }),
            FutureBuilder<String>(
                future: _barcodeString,
                builder:
                    (BuildContext context, AsyncSnapshot<String> snapshot) {
                  return Text(snapshot.data != null ? snapshot.data : '');
                }),
            Expanded(
//              child: ListView(children: _doWidgets()),
              child: childWidget(),
            ),
          ],
        ),
      ),
    );
  }

  void _getHttp() async {
    Map data = Map<String, dynamic>();
    data["schName"] = '明';

    BaseOptions options = BaseOptions(
      baseUrl: Const.baseUrl,
      method: 'POST',
//      method: 'GET',
//      headers: {'header': 'sss'},
      connectTimeout: 5000,
      receiveTimeout: 3000,
      responseType: ResponseType.plain,
    );
    try {
      // flutter packages pub run build_runner build
      Dio dio = Dio(options);
//      Response response =
//          await dio.post('/schInfo/queryByName', queryParameters: data);
      Response response = await dio.request('/schInfo/queryByName', queryParameters:data);


      if (loadingDialog != null) {
        loadingDialog = null;
        Navigator.pop(context);
      }

      Map<String, dynamic> decoded = json.decode(response.toString());
      CustomerBean customerBean = CustomerBean.fromJson(decoded);
      setState(() {
        dataList = customerBean.data;
      });
    } catch (e) {
      print(e);
    }
  }

  Widget childWidget() {
    Widget childWidget;
    if (dataList != null && dataList.length != 0) {
      childWidget = Padding(
        padding: EdgeInsets.all(6.0),
        child: ListView.builder(
            itemCount: dataList == null ? 0 : dataList.length,
            itemBuilder: (BuildContext context, int position) {
              List<Widget> temp = _doWidgets();
              return temp[position];
            }),
      );
    } else {
      childWidget = Stack(
        children: <Widget>[
          Padding(
            padding: EdgeInsets.fromLTRB(0.0, 35.0, 0.0, 0.0),
            child: Center(
              child: Text('正在加载中...'),
            ),
          ),
        ],
      );
    }
    return childWidget;
  }
}
